package org.chen.web.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.chen.common.RespUtils;
import org.chen.respmsg.RespEnum;
import org.chen.vo.RespBean;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        RespBean<String> result = RespUtils.result(RespEnum.LOGIN_FAIL);
        if (exception instanceof AuthenticationCredentialsNotFoundException){
            result.setMessage("找不到用户密码");
        }else if (exception instanceof UsernameNotFoundException){
            result.setMessage("没有该用户");
        }else if (exception instanceof BadCredentialsException){
            result.setMessage("密码无效");
        }else if (exception instanceof DisabledException){
            result.setMessage("该用户不可用");
        }
        PrintWriter writer = response.getWriter();
        String resp = new ObjectMapper().writeValueAsString(result);
        writer.write(resp);
        writer.flush();
        writer.close();
    }
}
